const { autoTransaction } = require('../util/db');
const { success, fail } = require('../util/core')
const { errorRes } = require('../config')
const { signToken } = require('../util/jwt');
class LoginService {
    async login(ctx, { data, session }) {
        const User = require('../models/User')
        const user = await User.findOne({ username: data.username }, null, { session })
        if (!user) {
            return fail(ctx, errorRes.noUser.message, errorRes.noUser.code);
        } else if (user.username !== data.username) {
            return fail(ctx, errorRes.noUsername.message, errorRes.noUsername.code);
        } else if (user.password !== data.password) {
            return fail(ctx, errorRes.noPassword.message, errorRes.noPassword.code);
        } else {
            const data = {
                _id: user._id,
                username: user.username,
                role: user.role,
                avatar: user.avatar,
                cover: user.cover
            }
            const token = signToken(data);
            const updatedUser = await User.findByIdAndUpdate(user._id, { token, lastLoginAt: Date() }, { new: true }, { session })
            if (updatedUser) {
                return success(ctx, updatedUser, '登录成功');
            }
        }
    }

    async register(ctx, { data, session }) {
        const User = require('../models/User')
        return await autoTransaction(async () => {
            const user = await User.findOne({ username: data.username }, null, { session })
            if (user) {
                return fail(ctx, errorRes.hasUser.message, errorRes.hasUser.code);
            } else {
                const newUser = (await User.create([data], { session }))[0]
                const data = {
                    _id: newUser._id,
                    username: newUser.username,
                    role: newUser.role,
                    avatar: newUser.avatar,
                    cover: newUser.cover
                }
                const token = signToken(data)
                return success(ctx, { token }, '注册成功');
            }
        })
    }
}

module.exports = new LoginService();